<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" :scroll="true">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="规则类型" prop="rulesCode">
        <el-select
          v-model="formData.rulesCode"
          placeholder="请选择规则类型"
          clearable
          @change="onRulseCodeChange"
          :disabled="formData.rulesId"
        >
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.METON_TRADE_RULSE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <template v-if="formData.rulesId">
        <el-form-item label="规则名称:" prop="rulesName">
          <el-input
            v-model="formData.rulesName"
            placeholder="请输入规则名称: 模板名称+规则名称或者规则名称"
          />
        </el-form-item>

        <el-form-item label="规则生效日期" prop="rulesDay">
          <el-date-picker
            v-model="formData.rulesDay"
            :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
            class="!w-240px"
            end-placeholder="规则结束日期"
            start-placeholder="规则开始日期"
            type="daterange"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="显示顺序" prop="sort">
          <el-input v-model="formData.sort" placeholder="请输入显示顺序" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="formData.status" placeholder="请选择状态" clearable>
            <el-option
              v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formData.remark" placeholder="请输入备注" />
        </el-form-item>
      </template>
    </el-form>
    <!-- 子表的表单 -->
    <template v-if="formData.rulesId">
      <el-divider content-position="left">规则设置</el-divider>
      <RulesItemForm ref="rulesItemFormRef" :rules-id="formData.rulesId" :rules-item="rulesItem" />
    </template>

    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { RulesApi, RulesVO } from '@/api/system/rules'

import RulesItemForm from './components/RulesItemForm.vue'
import { DICT_TYPE, getIntDictOptions, getStrDictOptions } from '@/utils/dict'
import { ElMessageBox } from 'element-plus'

/** 规则库 表单 */
defineOptions({ name: 'RulesForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  rulesId: undefined,
  rulesName: undefined,
  rulesCode: undefined,
  rulesDay: undefined,
  sort: undefined,
  status: undefined,
  remark: undefined,
  rulesItems: undefined
})
const formRules = reactive({
  rulesName: [
    { required: true, message: '规则名称: 模板名称+规则名称或者规则名称不能为空', trigger: 'blur' }
  ],
  rulesCode: [{ required: true, message: '规则code不能为空', trigger: 'blur' }],
  sort: [{ required: true, message: '显示顺序不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '状态不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const onRulseCodeChange = async () => {
  let rulesCode = formData.value.rulesCode
  let rulesCodeList = getStrDictOptions(DICT_TYPE.METON_TRADE_RULSE)

  let rulesName = rulesCodeList.find((ele) => {
    return ele.value == rulesCode
  })?.label
  ElMessageBox.confirm(`确认创建${rulesName}规则`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      preCreate()
    })
    .catch(() => {
      formData.value.rulesCode = undefined
    })
  // let params = {
  //   rulesCodes: [formData.value.rulesCode]
  // }
  // const data = await RulesApi.getRulesItemListByRulesCodes(params)
  // rulesItem.value = data[formData.value.rulesCode!]
}
const preCreate = async () => {
  let params = {
    rulesCode: formData.value.rulesCode
  }
  const data = await RulesApi.preCreateRules(params)
  formData.value.rulesId = data.rulesId
  formData.value = await RulesApi.getRules(data.rulesId)
  let paramss = {
    rulesCodes: [formData.value.rulesCode]
  }
  const datas = await RulesApi.getRulesItemListByRulesCodes(paramss)
  rulesItem.value = datas[formData.value.rulesCode!]
  nextTick(() => {
    rulesItemFormRef.value.setData(formData.value.rulesItems)
  })
}
/** 子表的表单 */
const subTabsName = ref('rulesItem')
const rulesItemFormRef = ref()
const rulesItem = ref()
/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await RulesApi.getRules(id)
      let paramss = {
        rulesCodes: [formData.value.rulesCode]
      }
      const datas = await RulesApi.getRulesItemListByRulesCodes(paramss)
      rulesItem.value = datas[formData.value.rulesCode!]
      nextTick(async () => {
        rulesItemFormRef.value.setData(formData.value.rulesItems)
      })
    } finally {
      formLoading.value = false
    }
  }
}

defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 校验子表单
  try {
    await rulesItemFormRef.value.validate()
  } catch (e) {
    subTabsName.value = 'rulesItem'
    return
  }
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as RulesVO
    // 拼接子表的数据
    data.rulesItems = rulesItemFormRef.value.getData()
    if (formType.value === 'create') {
      await RulesApi.createRules([data])
      message.success(t('common.createSuccess'))
    } else {
      await RulesApi.updateRules([data])
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    rulesId: undefined,
    rulesName: undefined,
    rulesCode: undefined,
    rulesDay: undefined,
    sort: undefined,
    status: undefined,
    remark: undefined,
    rulesItems: undefined
  }
  formRef.value?.resetFields()
}
</script>
